<template>
  <contentModel
    v-if="showModal"
    title="新增"
    :has-footer="false"
    @close="handleClose"
  >
    <div class="plan-alteration-receive-add-page-container">
      <query-form
        :component-config="formComponentConfig"
        :render-config="renderConfig"
        :render-keys="renderKeys"
        @search="searchHandle"
        @reset="resetHandle"
      />
      <table-container
        v-model:columns="columns"
        :loading="isLoading"
        :all-columns="allColumns"
        @refresh="getData"
      >
        <template #container-side>
          <a-space>
            <a-button
              v-permission="[
                'procurement:plan-list-change:batchConfirmPlanListChange',
              ]"
              @click="affirm"
              >确认</a-button
            >
            <a-button
              v-permission="[
                'procurement:plan-list-change:batchSavePlanListChange',
              ]"
              @click="cancel"
              >保存</a-button
            >
          </a-space>
        </template>
        <a-table
          v-model:selectedKeys="selectedKeys"
          :columns="columns"
          row-key="id"
          :data="renderData"
          :pagination="pagination"
          :row-selection="rowSelection"
          @page-change="pageChange"
          @page-size-change="pageSizeChange"
        >
          <template #secretLevel="{ record }">
            <secretLevelInfo
              :record="{
                secretLevel: record.secretLevel,
                secretLevelName: record.secretLevelName,
              }"
            />
          </template>
          <template #index="{ rowIndex }">
            <span> {{ startNumber + rowIndex + 1 }} </span>
          </template>
          <template #chngCauseDesc="{ record }">
            <a-input
              v-model="record.chngCauseDesc"
              placeholder="请填写变更原因"
            />
          </template>

          <template #chngPlanQty="{ record }">
            <a-input
              v-model="record.chngPlanQty"
              placeholder="请输入变更后订货数量"
            />
          </template>
          <template #chngPlanArrivalDate="{ record }">
            <a-date-picker
              v-model="record.chngPlanArrivalDate"
              format="YYYY-MM-DD"
              @change="onChange"
              @select="onSelect"
              @ok="onOk"
            />
          </template>
        </a-table>
      </table-container>
    </div>
  </contentModel>
</template>

<script lang="ts" setup>
  import {
    ref,
    defineAsyncComponent,
    onMounted,
    reactive,
    computed,
  } from 'vue';
  import queryForm from '@/common/components/query-form/index.vue';
  import tableContainer from '@/common/components/table-container/index.vue';
  import lodash from 'lodash';
  import {
    selectPlanListByPage,
    batchSavePlanListChange,
    batchConfirmPlanListChange,
  } from '@/api/purchase-plan/planAuthorized';
  import { Message, Modal } from '@arco-design/web-vue';
  import usePagination from '@/common/hooks/pagination';
  import secretLevelInfo from '@/common/components/secret-level-info/index.vue';
  import { renderKeys, renderConfig, columns } from './dataInfo';

  const formComponentConfig = {
    inputModal: () =>
      import('@/common/components/search-modal/input-modal.vue'),
  };

  const contentModel = defineAsyncComponent(
    () => import('@/common/components/content-model/index.vue')
  );

  defineProps({
    showModal: { type: Boolean, default: false },
  });
  // const total = ref(0);
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
    fixed: true,
  });
  const selectedKeys = ref([]);

  const selectedDate = ref(null);
  const handleClose = () => {
    emit('update:showModal', false);
  };
  const searchHandle = async (data: any) => {
    setCurrent(1);
    console.log('data数据', data);
    const params = {
      planListNo: data.planListNo ? data.planListNo : '',
      mdsItemCode: data.mdsItemCode ? data.mdsItemCode : '',
      millTypeCode: data.millTypeCode ? data.millTypeCode : '',
      batchNo: data.batchNo ? data.batchNo : '',
    };
    try {
      const res = (await selectPlanListByPage({
        businessStatus: 5,
        billPolicyStatus: 0,
        isChangeStatus: 0,
        ...params,
        ...queryPagination.value,
      })) as any;
      console.log(res, 'res添加');
      if (res.code === 200) {
        setTotal(res.data.total);
        renderData.value = res.data.list;
        console.log();
      }
    } finally {
      isLoading.value = false;
    }
  };
  const resetHandle = (data: any) => {
    console.log('resetHandle', data);
    getData();
  };
  const isLoading = ref(true);
  const allColumns = lodash.cloneDeep(columns);
  const renderData = ref<any[]>([]);

  const getData = async (queryInfo: object) => {
    renderData.value = [];
    isLoading.value = true;
    console.log('queryInfo添加', queryInfo);

    try {
      const res = (await selectPlanListByPage({
        businessStatus: 5,
        billPolicyStatus: 0,
        isChangeStatus: 0,
        ...queryPagination.value,
      })) as any;
      console.log(res, 'res添加');
      renderData.value = res.data.list;
      console.log(renderData.value, 'renderData.value');
      if (res.code === 200) {
        setTotal(res.data.total);
        renderData.value = res.data.list;
      }
    } finally {
      isLoading.value = false;
    }
  };
  const emit = defineEmits([
    'refresh',
    'update:showModal',
    'pageSizeChange',
    'pageChange',
  ]);
  // 确认
  const affirm = async () => {
    if (!selectedKeys.value.length) {
      Message.warning('请至少选择一条数据进行操作!');
      return;
    }
    const paramsArr = [];
    Modal.info({
      title: '提示',
      content: '您确定要确认当前所选的数据？',
      hideCancel: false,
      onOk: async () => {
        selectedKeys.value.forEach(async (element) => {
          const obj = renderData.value.filter((v) => v.id === element);
          console.log(element, obj);

          paramsArr.push({
            chngPlanQty: obj[0].chngPlanQty,
            planArrivalDate: obj[0].planArrivalDate,
            chngPlanArrivalDate: obj[0].chngPlanArrivalDate,
            chngCauseDesc: obj[0].chngCauseDesc,
          });
        });
        const changeStatus = paramsArr.every(
          (v) => v.chngCauseDesc !== '' && v.chngCauseDesc
        );
        const plsnStatus = paramsArr.every(
          (v) =>
            (v.chngPlanQty !== '' && v.chngPlanQty) ||
            (v.chngPlanArrivalDate !== '' && v.chngPlanArrivalDate)
        );
        if (!changeStatus) {
          Message.warning('请填写变更原因!');
          return;
        }
        if (!plsnStatus) {
          Message.warning('变更后订货数量或变更后计划到货日期至少填写一项!');
        }
        await affirmDate();
      },
    });
  };
  const affirmDate = async () => {
    const paramsArr = [];
    selectedKeys.value.forEach(async (element) => {
      const obj = renderData.value.filter((v) => v.id === element);
      console.log(element, obj);
      paramsArr.push({
        pmsPlanListId: obj[0].id,
        planQty: obj[0].planQty,
        chngPlanQty: obj[0].chngPlanQty,
        planArrivalDate: obj[0].planArrivalDate,
        chngPlanArrivalDate: obj[0].chngPlanArrivalDate,
        chngCauseDesc: obj[0].chngCauseDesc,
        secretLevel: obj[0].secretLevel,
      });
    });
    console.log(paramsArr, 'paramsArrparamsArr');

    try {
      const res = (await batchConfirmPlanListChange(paramsArr)) as any;
      console.log(res, 'res+');
      if (res.code === 200) {
        getData();
        selectedKeys.value = [];
        Message.success({
          content: '确认成功!',
        });
      }
      emit('refresh');
    } finally {
      isLoading.value = false;
    }
  };
  // 保存
  const cancel = () => {
    if (!selectedKeys.value.length) {
      Message.warning('请至少选择一条数据进行操作!');
      return;
    }
    const paramsArr = [];
    Modal.info({
      title: '提示',
      content: '是否要勾选保存的数据？',
      hideCancel: false,
      onOk: async () => {
        console.log(selectedKeys, 'selectedKeys');

        selectedKeys.value.forEach(async (element) => {
          const obj = renderData.value.filter((v) => v.id === element);
          console.log(element, obj);
          paramsArr.push({
            pmsPlanListId: obj[0].id,
            planQty: obj[0].planQty,
            chngPlanQty: obj[0].chngPlanQty,
            planArrivalDate: obj[0].planArrivalDate,
            chngPlanArrivalDate: obj[0].chngPlanArrivalDate,
            chngCauseDesc: obj[0].chngCauseDesc,
          });
        });
        const changeStatus = paramsArr.every(
          (v) => v.chngCauseDesc !== '' && v.chngCauseDesc
        );
        const plsnStatus = paramsArr.every(
          (v) =>
            (v.chngPlanQty !== '' && v.chngPlanQty) ||
            (v.chngPlanArrivalDate !== '' && v.chngPlanArrivalDate)
        );
        if (!changeStatus) {
          Message.warning('请填写变更原因!');
          return;
        }
        if (!plsnStatus) {
          Message.warning('变更后订货数量或变更后计划到货日期至少填写一项!');
          return;
        }
        try {
          const res = (await batchSavePlanListChange(paramsArr)) as any;
          if (res.code === 200) {
            getData();
            Message.success({
              content: '保存成功!',
            });
          }
          // emit('refresh');
        } finally {
          isLoading.value = false;
        }
      },
    });
  };
  const onSelect = () => {};
  const onChange = (value: any) => {
    selectedDate.value = value;
    console.log(selectedDate, 'selectedDate');
  };
  const onOk = async () => {
    // 更改计划到货日期  传参 id planArrivalDate(计划到货日期，格式“yyyy-MM-dd”)
  };

  onMounted(() => {
    getData();
  });

  const { pagination, setCurrent, setPageSize, setTotal, queryPagination } =
    usePagination();

  const pageChange = (val: number) => {
    setCurrent(val);
    getData();
  };
  const pageSizeChange = (val: number) => {
    setPageSize(val);
    getData();
    emit('pageSizeChange', lodash.cloneDeep(queryPagination.value));
  };
  const startNumber = computed(() => {
    return queryPagination.value.pageSize * (queryPagination.value.pageNo - 1);
  });
</script>

<style lang="less" scoped>
  .plan-alteration-receive-add-page-container {
    height: calc(100% - 32px);
    padding: 16px 24px;
    background: #fff;
  }
</style>
